import { showMessage } from '@/components/antd-comp/message'
import { showError } from '@/components/antd-comp/message/useNotification'
import SwitchComponent from '@/components/antd-comp/switch'
import ThemeBtn from '@/components/antd-comp/theme-btn'
import { ButtonNumber } from '@/components/bs-ui/button'
import { toast } from '@/components/bs-ui/toast/use-toast'
import { useFuncsStore } from '@/store/funcStore'
import { useBuriedEvent } from '@/util/buried'
import { Button, Input, Modal, Select } from 'antd'
import { throttle } from 'lodash'
import { useContext, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Checkbox } from '../../../components/ui/checkbox'
import { alertContext } from '../../../contexts/alertContext'
import { callWordAdd, callWordEdit } from '../API'
import '../css/styles.css'
const { TextArea } = Input

const CreateModal = ({ datalist, open, setOpen, obj, submitData }) => {
  
  /**
   * 功能权限限制
   */
  const { hasFuncPermission } = useFuncsStore()
  // ------埋点------
  const { callWordBuriedEvent } = useBuriedEvent()
  /* 取消 */
  const handleCancel = (e: React.MouseEvent<HTMLElement>) => {
    setOpen(false)
  }
  /* dialog内容 */
  const [person, setPerson] = useState({
    name: '',
    category: 0,
    content: '',
    contentNew: '',
    id: '',
    optimizeBtnHid: false
  })
  const { t } = useTranslation()
  // State for errors
  const [errors, setErrors] = useState<any>({})
  /* 迭代轮次=输入 */
  const [iteration_rounds, setIterationRounds] = useState(1)
  useEffect(() => {
    setPerson({
      ...person,
      ...obj
    })
  }, [])
  
  /* 提示报信信息 */
  const { setErrorData } = useContext(alertContext)
  const [error, setError] = useState({ name: false, desc: false })
  /* 提示词优化选项 */
  const checkedList = [
    {
      id: '1',
      name: t('call.callCheckSeleQuality'),
      checked: false
    },
    {
      id: '2',
      name: t('call.callCheckSeleShorten'),
      checked: false
    },
    {
      id: '3',
      name: t('call.callCheckSeleThinking'),
      checked: false
    }
  ]
  const [checked, setCheckedList] = useState(checkedList)
  /* 显示按钮状态 */
  const btnStatus = {
    loading: false,
    use: false
  }
  const optimizeBtnUsed = useRef(false)
  const [btnStatusType, setBtnStatusType] = useState(btnStatus)
  /* 优化按钮fun */
  const optimizeFun = () => {
    // 拥有创建或编辑权限自动拥有优化权限
    // if (!hasFuncPermission([Func.prompt.optimize])) {
    //   return
    // }
    optimizeBtnUsed.current = true
    const checkCli = []
    checked.forEach(item => {
      if (item.checked) {
        checkCli.push(item.id)
      }
    })
    const errorlist = []
    if (!person.content) errorlist.push(t('call.callTemCont'))
    if (person.content?.length > 1024) errorlist.push(t('call.callTemContJudgment'))
    if (checkCli.length === 0) errorlist.push(t('call.callTemOption'))
    if (!iteration_rounds) errorlist.push(t('call.callIteration'))
    if (Number(iteration_rounds) < 1 || Number(iteration_rounds) > 5) errorlist.push(t('call.callIterationTitle'))
    const nameErrors = errorlist.length
    setError({ name: !!nameErrors, desc: errorlist.length > nameErrors })
    if (errorlist.length) return handleError(errorlist)
    const obj = {
      prompt: person.content,
      types: checkCli.join(),
      iteration_rounds: Number(iteration_rounds)
    }
    setBtnStatusType({
      ...btnStatusType,
      use: false,
      loading: true
    })
    handleOptimizeReq(person.content, checkCli.join(), Number(iteration_rounds))
  }
  // 提示词优化
  const areaRef = useRef(null)
  const esLinkSuccess = useRef(false)
  const updateOptimizeInfo = throttle(list => {
    setPerson({
      ...person,
      contentNew: list.join('')
    })
    if (areaRef.current?.scrollHeight) {
      // 自动滚动
      areaRef.current.scrollTop = areaRef.current.scrollHeight
    }
  }, 100)
  const handleOptimizeReq = async (prompt, types, iteration_rounds) => {
    esLinkSuccess.current = false
    try {
      const apiUrl = `/api/v1/prompt_plt/optimize?prompt=${encodeURIComponent(
        prompt
      )}&types=${types}&iteration_rounds=${iteration_rounds}`
      const eventSource = new EventSource(apiUrl)
      const msgList = []
      eventSource.onmessage = event => {
        if (!event.data) {
          setBtnStatusType({
            ...btnStatusType,
            loading: false
          })
          return
        }
        esLinkSuccess.current = true
        const parsedData = JSON.parse(event.data)
        if (parsedData?.status && parsedData.status == 30) {
          updateOptimizeInfo(
            parsedData?.choices[0]?.delta?.content
              ? [parsedData.choices[0].delta.content]
              : [
                  '大模型advice:作为一名AI语言模型，我不能回答涉及色情、暴力、政治等敏感话题的问题。如果您有其他相关问题，请重新提问。'
                ]
          )
          return
        }
        switch (parsedData.type) {
          case 'prompt':
            msgList.push(parsedData.message)
            updateOptimizeInfo(msgList)
            break
          case 'error':
            updateOptimizeInfo([parsedData.message])
            setBtnStatusType({
              ...btnStatusType,
              use: true,
              loading: false
            })
            break
          case 'end':
            setBtnStatusType({
              ...btnStatusType,
              use: true,
              loading: false
            })
            if (parsedData.message) {
              showError(t('tip'), parsedData.message)
            }
            break
        }
      }

      eventSource.onerror = (error: any) => {
        console.log('eventSource.onerror', error)
        eventSource.close()
        // 尝试获取 JSON 数据判断是否为输入校验未通过
        let msg = '优化失败'
        fetch(apiUrl)
          .then(response => {
            if (response.ok && response.headers.get('Content-Type') === 'application/json') {
              return response.json()
            }
          })
          .then(data => {
            console.log('Received JSON data:', data)
            if (data.status_message) {
              msg = `${data.status_code}:${data.status_message}`
            }
          })
          .catch(error => {
            console.error('Failed to fetch or parse JSON:', error)
          })
          .finally(() => {
            if (error.data || !esLinkSuccess.current) {
              if (error.data) {
                msg = JSON.parse(error.data)
              }
              // showError(t('tip'), msg)
              toast({
                title: '提示',
                variant: 'error',
                description: msg
              })
            }
            setBtnStatusType({
              ...btnStatusType,
              use: esLinkSuccess.current,
              loading: false
            })
          })
      }
    } catch (error) {
      setBtnStatusType({
        ...btnStatusType,
        loading: false
      })
    }
  }
  /* 优化确定 */
  const optimizeOK = () => {
    setPerson({
      ...person,
      content: person.contentNew,
      contentNew: ''
    })
    setBtnStatusType({
      ...btnStatusType,
      use: false
    })
  }
  const close = () => {
    setOpen(false)
    submitData()
  }
  /* 提交表单 */
  const handleCreate = () => {
    const isValid = validateForm()
    if (isValid) {
      /* 优化判断 重置content */
      const obj = {
        ...person
      }

      const buriedInfo = {
        page: obj.id ? '编辑提示词弹窗' : '创建提示词弹窗',
        event_name: '【确定】按钮',
        data_id: obj.id
      }
      const buriedDetails = {
        结果: '成功',
        类型: obj.category,
        使用优化按钮: optimizeBtnUsed.current ? '是' : '否'
      }
      if (obj.id) {
        callWordEdit({
          ...obj
        })
          .then((res: any) => {
            callWordBuriedEvent({ ...buriedInfo, detail: JSON.stringify(buriedDetails) })
            close()
            showMessage({
              content: '修改成功',
              type: 'success'
            })
          })
          .catch(() => {
            buriedDetails['结果'] = '失败'
            callWordBuriedEvent({ ...buriedInfo, detail: JSON.stringify(buriedDetails) })
          })
      } else {
        callWordAdd({
          ...obj
        })
          .then((res: any) => {
            close()
            console.log('编辑提示词弹窗', res)
            buriedInfo.data_id = res.id
            callWordBuriedEvent({ ...buriedInfo, detail: JSON.stringify(buriedDetails) })
            showMessage({
              content: '新建成功',
              type: 'success'
            })
          })
          .catch(() => {
            buriedDetails['结果'] = '失败'
            callWordBuriedEvent({ ...buriedInfo, detail: JSON.stringify(buriedDetails) })
          })
      }
    }
  }
  const handleError = list => {
    setErrorData({
      title: t('prompt'),
      list
    })
  }
  /* 更新checkList dialog的提示词优化选项 */
  function checkedSele(id) {
    setCheckedList(
      checked.map(artwork => {
        if (artwork.id === id) {
          // 创建包含变更的*新*对象
          return { ...artwork, checked: !artwork.checked }
        } else {
          // 没有变更
          return artwork
        }
      })
    )
  }
  // Validate form fields
  const validateField = (name, value) => {
    switch (name) {
      case 'name':
        if (!value) return t('build.nameRequired')
        if (value.length > 50) return t('build.nameMaxLength')
        return ''
      // case 'category':
      //   if (!value) return t('system.roleCategoryRequired')
      //   return ''
      case 'content':
        if (value && value.length > 1024) return t('call.callTemContJudgment')
        return ''
      default:
        return ''
    }
  }
  // Handle field change
  const handleChange = (e, type) => {
    const error = validateField(type, e)
    setErrors(prev => ({ ...prev, [type]: error }))
    if (type === 'name') {
      setPerson({ ...person, name: e })
    } else if (type === 'category') {
      setPerson({ ...person, category: e })
    } else if (type === 'content') {
      setPerson({ ...person, content: e, contentNew: '' })
      setBtnStatusType({
        ...btnStatusType,
        loading: false,
        use: false
      })
    }
  }
  // Validate entire form
  const validateForm = () => {
    const formErrors = {}
    let isValid = true
    Object.keys(person).forEach(key => {
      const error = validateField(key, person[key])
      if (error) {
        formErrors[key] = error
        isValid = false
      }
    })
    setErrors(formErrors)
    return isValid
  }
  // 滚动到最底部ref
  const caseScrollRef = useRef(null)
  return (
    <>
      <Modal
        width={825}
        className="modal_antcomp_case max-h-[40%]"
        title={person.id ? t('call.callDiaNameEdit') : t('call.callDiaName')}
        open={open}
        style={{ top: '10%' }}
        // onOk={handleOk}
        onCancel={handleCancel}
        maskClosable={false}
        footer={[
          <Button
            key="cancel"
            className="closeBtnStyles closeBtnWid"
            shape="round"
            onClick={() => {
              callWordBuriedEvent({
                page: person.id ? '编辑提示词弹窗' : '创建提示词弹窗',
                event_name: '【取消】按钮'
              })
              setOpen(false)
            }}
          >
            {t('cancel')}
          </Button>,
          <ThemeBtn key="create" className="closeBtnWid" onClick={() => handleCreate()}>
            {person.id ? t('confirmButton') : t('create')}
          </ThemeBtn>
        ]}
      >
        <div
          ref={caseScrollRef}
          style={{ overflowY: 'scroll', height: '400px' }}
          className="caseOverFlowY flex flex-col gap-4 py-2 pr-1 sm:max-w-[825px]"
        >
          {/* 名称 */}
          <div className="">
            <label htmlFor="name" className="bisheng-label labelSizePort">
              {t('call.callTemName')}
              <span className="bisheng-tip">*</span>
            </label>
            <Input
              name="name"
              autoComplete="off"
              value={person.name}
              onChange={e => handleChange(e.target.value, 'name')}
              placeholder={t('call.callTemName')}
              className={`col-span-3 ${error.name && 'border-red-400'} contMarginTop inoutHig`}
            />
            {errors.name && <p className="bisheng-tip mt-1">{errors.name}</p>}
          </div>
          {/* 类型 */}
          {/* <div className="caseMarginTop">
            <label htmlFor="model" className="bisheng-label labelSizePort">
              {t('call.callTemTyp')}
              <span className="bisheng-tip">*</span>
            </label>
            <div className="contMarginTop">
              <Select
                key={'calldialog_select'}
                className="inoutHig"
                placeholder={t('call.callTemTyp')}
                value={person.category ? person.category : null}
                style={{ width: '100%' }}
                onChange={val => handleChange(val, 'category')}
                options={datalist}
                fieldNames={{ label: 'label', value: 'id' }}
              />
            </div>
            {errors.category && <p className="bisheng-tip mt-1">{errors.category}</p>}
          </div> */}
          {/* 变量识别符 */}
          <div className="caseMarginTop">
            <label className="bisheng-label labelSizePort">{t('call.callTemiable')}</label>
            <Input
              disabled
              value={'{{}}'}
              placeholder={t('call.callTemiable')}
              className={'contMarginTop inoutHig col-span-3'}
            />
          </div>
          {/* 提示词内容 */}
          <div className="caseMarginTop">
            <label htmlFor="content" className="bisheng-label labelSizePort">
              {t('call.callTemCont')}
            </label>
            <TextArea
              value={person.content}
              className={`col-span-3 ${error.desc && 'border-red-400'} contMarginTop`}
              placeholder={t('call.callTemCont')}
              style={{ minHeight: 144, resize: 'none', position: 'inherit' }}
              onChange={e => {
                handleChange(e.target.value, 'content')
                setTimeout(() => {
                  caseScrollRef.current.scrollTop = caseScrollRef.current.scrollHeight
                })
              }}
            />
            {errors.content && <p className="bisheng-tip mt-1">{errors.content}</p>}
          </div>
          {/* 优化 */}
          <div className="caseMarginTop">
            {/* <div className="flexRowStart">
              <label htmlFor="roleAndTasks" className="bisheng-label labelSizePort">
                {t('call.callOptimize')}
              </label>
              <div className="callWord_calldia_switchCase">
                <SwitchComponent
                  style={{ marginLeft: '10px' }}
                  checked={person.optimizeBtnHid}
                  onChange={() => {
                    setPerson({
                      ...person,
                      optimizeBtnHid: !person.optimizeBtnHid
                    })
                    setTimeout(() => {
                      caseScrollRef.current.scrollTop = caseScrollRef.current.scrollHeight
                    })
                  }}
                />
              </div>
            </div> */}
            {/* 优化内容选项 */}
            {person.optimizeBtnHid ? (
              <>
                <div className="flexRowStart contMarginTop max-w-[99%]">
                  {checkedList.map(item => {
                    return (
                      <div className="flexRow call-dialog-checkbox" style={{ marginRight: '16px' }} key={item.id}>
                        <Checkbox
                          onCheckedChange={(event: boolean) => {
                            checkedSele(item.id)
                          }}
                          style={{ marginRight: '5px' }}
                          id={item.id}
                          key={item.id}
                        ></Checkbox>
                        {item.name}
                      </div>
                    )
                  })}
                  <div className="flexRow roundsBox">
                    {t('call.callIteration')}
                    <div className="roundsBox_put">
                      <ButtonNumber
                        value={iteration_rounds}
                        onChange={val => setIterationRounds(val)}
                        max={5}
                        min={1}
                        step={1}
                      />
                    </div>
                  </div>
                </div>
                {/* 优化后的内容 */}
                <div className="flexRow flexRowJustBet callOptimizeBox" style={{ position: 'relative' }}>
                  <TextArea
                    className={`col-span-3 ${error.desc && 'border-red-400'}`}
                    value={person.contentNew}
                    onChange={e => setPerson({ ...person, contentNew: e.target.value })}
                    placeholder={t('call.callTemCont')}
                    style={{ height: 144, resize: 'none' }}
                  />
                  {/* 优化按钮 - use 确定 取消 or 优化 and loading */}
                  {btnStatusType.use ? (
                    <>
                      <Button
                        type="primary"
                        size="small"
                        className="application_btn"
                        style={{ right: '78px', background: '#5964F3' }}
                        onClick={optimizeOK}
                      >
                        {t('build.use')}
                      </Button>
                      <Button size="small" className="application_btn" style={{ right: '12px' }} onClick={optimizeFun}>
                        {t('build.retry')}
                      </Button>
                    </>
                  ) : (
                    <Button
                      type="primary"
                      size="small"
                      className="application_btn"
                      disabled={!person.content}
                      loading={!!btnStatusType.loading}
                      style={person.content ? { background: '#5964F3', right: '12px' } : { right: '12px' }}
                      onClick={optimizeFun}
                    >
                      {btnStatusType.loading ? t('call.callOptimizeBtnLoading') : t('call.callOptimizeBtn')}
                    </Button>
                  )}
                </div>
              </>
            ) : null}
          </div>
        </div>
      </Modal>
    </>
  )
}

export default CreateModal
